import { Injectable, HttpStatus } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { CreateUserDto } from './user.dto'
import { User } from './user.entity'
import { UserCreateResp } from './user.interface'

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private readonly userRepository: Repository<User>,
  ) {}

  async findAll(): Promise<User[]> {
    return await User.find()
  }

  async create(createUserDto: CreateUserDto): Promise<UserCreateResp> {
    const { username, password } = createUserDto
    if ( !username ) { return { code: HttpStatus.NOT_ACCEPTABLE, message: 'No username' } }

    const user = new User()
    user.username = username
    user.password = password

    const doc = await User.findOne({ username: createUserDto.username })
    if (doc) { return { code: HttpStatus.CONFLICT, message: 'User exist' } }

    return user
      .save()
      .then(res => ({ code: HttpStatus.CREATED, message: 'create employee ...done' }))
      .catch(err => ({ code: HttpStatus.INTERNAL_SERVER_ERROR, message: err }))
  }

  async findOne(username: string): Promise<User> {
    return await User.findOne({ username })
  }
}
